<template>

  <el-dialog :visible.sync="dialogFormVisible" title="新增章节">
    <el-form :model="chapter">
      <el-form-item :label-width="formLabelWidth" label="章节标题">
        <el-input v-model="chapter.title" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="章节排序">
        <el-input-number v-model="chapter.sort" :min="0" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import chapterApi from '@/api/chapter'
export default {
  data() {
    return {
      dialogFormVisible: false,
      formLabelWidth: '80px',
      chapter: {}
    }
  },
  methods: {
    open(chapterId) {
      // 设置对话框的标题
      this.dialogFormVisible = true
      this.title = '更新章节'
      // 对话框页面查询到章回显后
      chapterApi.getChapter(chapterId).then(r => {
        this.chapter = r.data.item
        // 弹出对话框显示
      })
    },
    // 取消提交章节的信息，重置章节信息，并将标签的可视化变成false
    close() {
      this.chapter = {}
      this.dialogFormVisible = false
    },
    // 提交章节的信息到数据库
    submit() {
      // 调用js封装的方法提交数据
      // 将课程的id绑定给章节信息
      if (this.chapter.id) {
        this.update()
      } else {
        this.save()
      }
    },
    save() {
      this.chapter.courseId = this.$parent.$parent.courseId
      chapterApi.addChapter(this.chapter).then(r => {
        this.$message.success('添加成功')
        this.$parent.getChapterAndVideo()
        this.close()
      })
    },
    update() {
      chapterApi.editChapter(this.chapter).then(r => {
        this.$message.success('更新' + this.chapter.title + '章成功')
        this.$parent.getChapterAndVideo()
        this.close()
      })
    }
  }
}
</script>
